package itsm.isperp.framework.sequence;

import itsm.isperp.framework.core.context.ContextHolder;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

/**
 * 流水号构造器，这是一个运行在现场安全下构造基于数据库规则的流水号生成器。
 * 
 * <p>
 * 使用方法： <code>
 * SequenceGenerater.instance().next();
 * </code>
 * </p>
 * 
 * @author lizx
 * @date 2013-3-5
 * @version V1.0
 */
@Component
public class SequenceGenerator {

	private static SequenceGenerator sequenceGenerator = null;

	// 换成rule

	// org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer
	/**
	 * 隐藏构造器
	 */
	protected SequenceGenerator() {
	}

	@Resource
	protected SequenceIncrementer sequenceIncrementer;

	public SequenceIncrementer getSequenceIncrementer() {
		return sequenceIncrementer;
	}

	public void setSequenceIncrementer(SequenceIncrementer sequenceIncrementer) {
		this.sequenceIncrementer = sequenceIncrementer;
	}

	public static SequenceGenerator instance() {
		if (sequenceGenerator == null) {
			synchronized (SequenceGenerator.class) {
				sequenceGenerator = new SequenceGenerator();
			}
		}
		return sequenceGenerator;
	}

	public synchronized String next(String tableName) {
		sequenceIncrementer.setTableName(tableName);
		return sequenceIncrementer.nextStringValue();
	}

	public static SequenceRule getRule(String tableName) {

		return ContextHolder.getApplicationSequenceCache().get(tableName);

	}

}
